//
//  LoginView.swift
//  SwiftUiBaseStudy
//
//  Created by Daniel on 2023/12/10.
//

import SwiftUI
import Firebase

struct LoginView: View {
    
    @State var email = "123456@qq.com"
    @State var password = "123456"
    
    
    
    var shadowColor = Color(#colorLiteral(red: 0.1647058824, green: 0.1882352941, blue: 0.3882352941, alpha: 1))
    var iconColor = Color(#colorLiteral(red: 0.6549019608, green: 0.7137254902, blue: 0.862745098, alpha: 1))
    var emailIcon = "person.crop.circle.fill"
    var passwordIcon = "lock.fill"
    
    var btnBg = Color(#colorLiteral(red: 0, green: 0.7529411765, blue: 1, alpha: 1))
    
    @State var showAlert = false
    @State var alertMessage = "Something went wrong."
    
    @State var isFocused = false
    
    @State var isLoading = false
    @State var isSuccessFul = false
    
    @EnvironmentObject var user:UserStore
    
    func hideKeyboard(){
        UIApplication.shared.sendAction(#selector(UIResponder().resignFirstResponder), to: nil, from: nil, for: nil)
    }
    
    func login(){
        isLoading = true
        Auth.auth().signIn(withEmail: email, password: password) { result, error in
            isLoading = false
            if error != nil{
                alertMessage = error?.localizedDescription ?? "未知错误"
                showAlert = true
            }else{
                isSuccessFul = true
                user.isLogged = true
//                UserDefaults.standard.set(true, forKey: "isLogged")
                DispatchQueue.main.asyncAfter(deadline: .now()+2){
                    isSuccessFul = false
                    email = ""
                    password = ""
                    
                    
                    user.showLogin = false
                }
            }
        }
    }
    
    
    var body: some View {
        ZStack{
    
            Color.black.ignoresSafeArea(.all)
            Color("background2").ignoresSafeArea(edges:.bottom)
                .clipShape(RoundedRectangle(cornerRadius: 30, style: .continuous))
                .onTapGesture {
                    isFocused = false
                    hideKeyboard()
                }
            ZStack(alignment:.top) {
                
                CoverView()
                
                VStack {
                    
                    
                    HStack {
                        Image(systemName: emailIcon)
                            .foregroundStyle(iconColor)
                            .frame(width: 44,height: 44)
                            .background(.white)
                            .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                            .shadow(color: shadowColor.opacity(0.1), radius:5,x:0,y:5)
                            .padding(.leading)
                        TextField("Your Email".uppercased(),text:$email)
                            .keyboardType(.emailAddress)
                            .font(.subheadline)
                            .padding(.leading)
                            .frame(height:44)
                            .onTapGesture {
                                isFocused = true
                            }
                    }
                    
                    Divider()
                        .padding(.leading,80)
                    
                    HStack {
                        Image(systemName: passwordIcon)
                            .foregroundStyle(iconColor)
                            .frame(width: 44,height: 44)
                            .background(.white)
                            .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                            .shadow(color: shadowColor.opacity(0.1), radius:5,x:0,y:5)
                            .padding(.leading)
                        SecureField("Your Password".uppercased(),text:$password)
                            .keyboardType(.default)
                            .font(.subheadline)
                            .padding(.leading)
                            .frame(height:44)
                            .onTapGesture {
                                isFocused = true
                            }
                    }
                }
                .frame(height: 136)
                .frame(maxWidth: 712)
                .background(BlurView(style: .systemMaterial))
                .clipShape(RoundedRectangle(cornerRadius: 30, style: .continuous))
                .shadow(color: shadowColor.opacity(0.2), radius:20,x:0,y:20)
                .padding(.horizontal,16)
                .offset(y:460)
                
                
                HStack{
                    Text("forget password")
                        .font(.subheadline)
                    Spacer()
                    Button(action: {
//                        showAlert = true
                        login()
                    }, label: {
                        Text("Log in".uppercased())
                            .foregroundStyle(.black)
                    })
                    .padding(16)
                    .padding(.horizontal,30)
                    .background(btnBg)
                    .clipShape(RoundedRectangle(cornerRadius: 30))
                    .shadow(color:btnBg.opacity(0.2), radius:10,x:0,y:10)
                    .alert(alertMessage, isPresented: $showAlert) {
                        Button("ok",role:.cancel) {
                            
                        }
                        
                        Button("cancel",role:.destructive) {
                            
                        }

                    }message: {
                        Text("it's message")
                    }
                }
                .frame(maxWidth: 712,maxHeight:.infinity,alignment:.bottom)
                .padding()
                .offset(y:isFocused ? 300:0)
                
                
            }
            .offset(y:isFocused ? -300:0)
            .animation(.easeInOut, value: isFocused)
            .onTapGesture {
                isFocused = false
                hideKeyboard()
            }
            if(isLoading){
                LoadingView()
            }
            
            if(isSuccessFul){
                SuccessView()
            }
        }
    }
}

#Preview {
    LoginView()
}

struct CoverView: View {
    
    var bgColor = Color(#colorLiteral(red: 0.4117647059, green: 0.4705882353, blue: 0.9725490196, alpha: 1))
    
    @State var show = false
    @State var viewState = CGSize.zero
    @State var isDragging = false
    
    
    
    var body: some View {
        VStack {
            GeometryReader { geometry in
                Text("Learng swift ui & \ndata. form")
                    .font(.system(size: geometry.size.width / 10,weight: .bold))
                    .multilineTextAlignment(.center)
                    .foregroundStyle(.white)
                    .frame(maxWidth: .infinity)
                    .offset(x:viewState.width/15,y: viewState.height/15)
            }
            .frame(maxWidth: 375,maxHeight: 100)
            
            Text("80 hours course for swift ui")
                .font(.subheadline)
                .multilineTextAlignment(.center)
                .offset(x:viewState.width/20,y: viewState.height/20)
            Spacer()
        }
        .padding(.top,100)
        .frame(height: 477)
        .frame(maxWidth: .infinity)
        .background(
            ZStack{
                // 旋转动画
                Image("Blob")
                    .offset(x:-150,y:-200)
                    .rotationEffect(Angle(degrees: show ? 360+90 : 90))
                    .blendMode(.plusDarker)
                    .animation(.linear(duration: 120)
                        .repeatForever(autoreverses: false), value: show)
                Image("Blob")
                    .offset(x:-200,y:-200)
                    .rotationEffect(Angle(degrees: show ? 360 : 0),anchor: .leading)
                    .blendMode(.overlay)
                    .animation(.linear(duration: 120)
                        .repeatForever(autoreverses: false), value: show)
            }
                .onAppear{
                    show = true
                }
        )
        .background(
            Image("Card3")
                .offset(x:viewState.width/25,y: viewState.height/25)
                .scaleEffect(isDragging ? 1.05:1)
            ,alignment: .bottom)
        .background(bgColor)
        .clipShape(RoundedRectangle(cornerRadius: 30, style: .continuous))
        .scaleEffect(isDragging ? 0.9 : 1)
        .animation(.timingCurve(0.2, 0.8, 0.2, 1, duration: 0.8), value: isDragging)
        .rotation3DEffect(
            Angle(degrees: 5),
            axis: (x: viewState.width, y: viewState.height, z: 0.0)
        )
        .gesture(
            DragGesture()
                .onChanged({ value in
                    viewState = value.translation
                    isDragging = true
                })
                .onEnded({ value in
                    viewState = .zero
                    isDragging = false
                })
        )
    }
}
